package com.herui.ota.test;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class TreeNode {
    String val;
    List<TreeNode> children;

    TreeNode(String val) {
        this.val = val;
        this.children = new ArrayList<>();
    }
}

public class TreeParser {
    private Map<Integer, List<String>> leafNodesByLevel;

    public TreeParser() {
        leafNodesByLevel = new HashMap<>();
    }

    public TreeNode parseTree(List<String> data) {
        TreeNode root = new TreeNode("");
        for (String nodeStr : data) {
            addNode(root, nodeStr, 0);
        }
        return root;
    }

    private void addNode(TreeNode root, String nodeStr, int level) {
        String[] levels = nodeStr.split("-");
        TreeNode currentNode = root;
        for (String i : levels) {
            currentNode = findOrCreateChild(currentNode, i);
        }
        if (currentNode.children.isEmpty()) {
            if (!leafNodesByLevel.containsKey(level)) {
                leafNodesByLevel.put(level, new ArrayList<>());
            }
            leafNodesByLevel.get(level).add(currentNode.val);
        }
    }

    private TreeNode findOrCreateChild(TreeNode parent, String val) {
        for (TreeNode child : parent.children) {
            if (child.val.equals(val)) {
                return child;
            }
        }
        TreeNode newNode = new TreeNode(val);
        parent.children.add(newNode);
        return newNode;
    }

    public Map<Integer, List<String>> getLeafNodesByLevel() {
        return leafNodesByLevel;
    }

    public static void main(String[] args) {
        List<String> data = new ArrayList<>();
        data.add("0-0-2-0");
        data.add("0-0-0");
        data.add("0-0-1");
        data.add("0-0-1-0");
        data.add("0-0-1-1");
        data.add("0-0-1-2");

        TreeParser treeParser = new TreeParser();
        TreeNode root = treeParser.parseTree(data);
        printTree(root, 0);

        Map<Integer, List<String>> leafNodesByLevel = treeParser.getLeafNodesByLevel();

        for (Map.Entry<Integer, List<String>> entry : leafNodesByLevel.entrySet()) {
            int level = entry.getKey();
            List<String> leafNodes = entry.getValue();
            System.out.println("Level " + level + " leaf nodes:");
            for (String node : leafNodes) {
                System.out.println("  Node: " + node);
            }
        }
    }

    private static void printTree(TreeNode node, int depth) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            sb.append("  ");
        }
        sb.append(node.val);
        System.out.println(sb.toString());
        for (TreeNode child : node.children) {
            printTree(child, depth + 1);
        }
    }
}
